﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NHibernate;

namespace Data
{
    public class Repository<T> where T : class
    {
        private readonly ISession _session;

        public Repository(ISession session)
        {
            _session = session;
        }

        public bool Del(T entity)
        {
            try
            {
                _session.Delete(entity);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public bool Del(IEnumerable<T> items)
        {
            try
            {
                foreach (T item in items)
                {
                    _session.Delete(item);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public bool Add(T entity)
        {
            try
            {
                _session.Save(entity);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public bool Add(IEnumerable<T> items)
        {
            try
            {
                foreach (T item in items)
                {
                    _session.Save(item);
                }
                return true;

            }
            catch (Exception ex)
            {
                return true;
            }
        }
        public bool Update(T entity)
        {
            try
            {
                _session.Update(entity);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public IList<T> All()
        {
            try
            {
                return _session.CreateCriteria<T>().List<T>();
            }
            catch (Exception ex)
            {
                return new List<T>();
            }
        }
        public IList<T> Find(Expression<Func<T, bool>> where)
        {
            return All().AsQueryable().Where(where).ToList();
        }

        public T Single(Expression<Func<T, bool>> where)
        {
            return All().AsQueryable().Single(where);
        }
        public T SingleOrDefault(Expression<Func<T, bool>> where)
        {
            return All().AsQueryable().SingleOrDefault(where);
        }
        public T First(Expression<Func<T, bool>> where)
        {
            return All().AsQueryable().First(where);
        }
        public T FirstOrDefault(Expression<Func<T, bool>> where)
        {
            return All().AsQueryable().FirstOrDefault(where);
        }
    }
}
